package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.NursingTaskDto;
import com.zzyl.nursing.dto.TaskDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.NursingTaskVo;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

/**
 * 护理任务Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-02
 */
@Service
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper,NursingTask> implements INursingTaskService
{
    @Autowired
    private NursingTaskMapper nursingTaskMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private NursingElderMapper nursingElderMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ICheckInService checkInService;



    /**
     * 查询护理任务
     * 
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTaskVo queryNursingTaskById(Long id)
    {
        NursingTask nursingTask = nursingTaskMapper.selectNursingTaskById(id);
        Long elderId = nursingTask.getElderId();
        //护理等级名称
        LambdaQueryWrapper<CheckIn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckIn::getElderId, elderId);
        CheckIn checkIn = checkInService.getOne(queryWrapper);
        String nursingLevelName = checkIn.getNursingLevelName();
        //获取护理员名称
        List<SysUser> sysUsers = nursingElderMapper.selectUserByElderId(nursingTask.getElderId());
        List<String> list = sysUsers.stream().map(SysUser::getNickName).collect(Collectors.toList());

        //复制到vo
        NursingTaskVo nursingTaskVo = BeanUtil.copyProperties(nursingTask, NursingTaskVo.class);
        //年龄
        Elder elder = elderMapper.selectElderById(elderId);
        String idCardNo = elder.getIdCardNo();
        String birthStr = idCardNo.substring(6, 14);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthStr, formatter);
        int age = Period.between(birthDate, LocalDate.now()).getYears();
        //性别
        String gender = null;
        char sexChar = idCardNo.charAt(16);
        if (sexChar % 2 == 0) {
            gender =  "女";
        } else {
            gender =  "男";
        }
        //获取执行人
        if(StrUtil.isNotEmpty(nursingTask.getUpdateBy())){
            SysUser user = sysUserMapper.selectUserById(Long.valueOf(nursingTask.getUpdateBy()));
            nursingTaskVo.setUpdater(user.getNickName());
        }
        //封装
        nursingTaskVo.setAge(age);
        nursingTaskVo.setNursingName(list);
        nursingTaskVo.setNursingLevelName(nursingLevelName);
        nursingTaskVo.setSex(gender);
        nursingTaskVo.setRealServerTime(LocalDateTimeUtil.now());
        return nursingTaskVo;
    }

    /**
     * 查询护理任务列表
     * 
     * @param dto 护理任务
     * @return 护理任务
     */
    @Override
    public List<NursingTaskVo> selectNursingTaskList(NursingTaskDto dto)
    {
        QueryWrapper<NursingTask> queryWrapper = new QueryWrapper<>();
        Page<NursingTask> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        // 可以在这里设置查询条件
        if(ObjUtil.isNotEmpty(dto.getElderName())){
            queryWrapper.like("elder_name", dto.getElderName());
        }
        if(ObjUtil.isNotEmpty(dto.getNurseId())){
            queryWrapper.eq("nursing_id", dto.getNurseId());
        }
        if(ObjUtil.isNotEmpty(dto.getProjectId())){
            queryWrapper.eq("project_id", dto.getProjectId());
        }
        if(ObjUtil.isNotEmpty(dto.getStartTime())&&ObjUtil.isNotEmpty(dto.getEndTime())){
            queryWrapper.between("estimated_server_time", dto.getStartTime(), dto.getEndTime());
        }
        if(ObjUtil.isNotEmpty(dto.getStatus())){
            queryWrapper.eq("status", dto.getStatus());
        }
        List<NursingTask> list = list(queryWrapper);
        List<NursingTaskVo> nursingTaskVos = new ArrayList<>();
        list.forEach(nursingTask -> {
            NursingTaskVo nursingTaskVo = BeanUtil.copyProperties(nursingTask,NursingTaskVo.class);
            String nursingId = nursingTask.getNursingId();
            if (StrUtil.isNotEmpty(nursingId)){
                String[] split = nursingId.split(",");
                List<String> nursingNames = new ArrayList<>();
                for (String s : split) {
                    String nursingName = sysUserMapper.selectUserByUserId(Long.valueOf(s));
                    if (StrUtil.isNotEmpty(nursingName)){
                        nursingNames.add(nursingName);
                    }
                }
                nursingTaskVo.setNursingName(nursingNames);
            }
            nursingTaskVos.add(nursingTaskVo);
        });
        return nursingTaskVos;
    }
    /**
     * 取消护理任务
     * 
     * @param taskDto 护理任务
     * @return 结果
     */
    @Override
    public int cancelNursingTask(TaskDto taskDto)
    {
        NursingTask nursingTask = nursingTaskMapper.selectNursingTaskById(taskDto.getTaskId());
        nursingTask.setCancelReason(taskDto.getReason());
        nursingTask.setStatus(3);
        return updateById(nursingTask)?1:0;
    }

    /**
     * 执行护理任务
     */
    @Override
    public int startNursingTask(TaskDto taskDto) {
        NursingTask nursingTask = nursingTaskMapper.selectNursingTaskById(taskDto.getTaskId());
        BeanUtil.copyProperties(taskDto,nursingTask);
        if (nursingTask.getStatus() == 1) {
            nursingTask.setStatus(2);
        }
        return updateById(nursingTask)?1:0;
    }

    /**
     * 护理任务改期
     */
    @Override
    public int updateTimeNursingTask(TaskDto taskDto) {
        NursingTask nursingTask = nursingTaskMapper.selectNursingTaskById(taskDto.getTaskId());
        if (nursingTask.getStatus() == 1) {
            nursingTask.setEstimatedServerTime(taskDto.getEstimatedServerTime());
            return updateById(nursingTask)?1:0;
        } else {
            return 0;
        }
    }

    @Transactional
    @Override
    public void updateNursingTaskStatus() {
        LambdaQueryWrapper<NursingTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NursingTask::getStatus,1);
        //期望服务时间小于当前时间
        queryWrapper.le(NursingTask::getEstimatedServerTime, LocalDateTime.now());
        List<NursingTask> list = list(queryWrapper);

        if(list!=null && !list.isEmpty()){
            list.forEach(item-> item.setStatus(3));
            updateBatchById(list);
        }
    }

    @Override
    public void createNursingTaskJob() {

    }


}
























